import { conn } from '../../@beshell/conn-ts/Connection';
import { AppModel } from '../../../../model/AppModel';
import { createUIWidgetMenu } from '../BlockPackage'

export default {

    category: Blockly.Categories.event ,
    
    color: [
        Blockly.Colours.operators.primary,
        Blockly.Colours.operators.secondary,
        Blockly.Colours.operators.tertiary
    ] ,

    previousStatement: false ,
    nextStatement: true ,
    hat: true ,
    
    eventHandle: true ,

    init(model: AppModel) {
        this.appendDummyInput()
                .appendField("当UI摇杆")
                .appendField(createUIWidgetMenu(model, "Rocker"), 'uirocker')
                .appendField("被摇动")
    } ,

    run (args: any, util: any, runtime: any, model: AppModel) {
        if(!conn.isConnected) {
            return
        }

        let widget = model.ui.mapWidgets[args.uirocker]
        let data = runtime.uiwidgetEvent[args.uirocker]

        // 向远程零件转发
        if(data && widget) {
            let code = `be.bus.emit("ui-event.${widget.name}.input", ${data.x}, ${data.y})`
            conn.console.run(code)
        }

        return true
    } ,

    coder: {
        JavaScript(block: any, coder: any, model: AppModel) {

            let wid = block.getFieldValue('uirocker')
            let widget = model.ui.mapWidgets[wid]
            
            let inner = ''
            let nextBlock = block.nextConnection && block.nextConnection.targetBlock()
            if(nextBlock) {
                coder.indent ++
                inner = coder.blockToCode(nextBlock)
                coder.indent --
            }

            return `${coder.indentString()}be.bus.on( "ui-event.${widget.name}.input", async (x, y)=>{\n`
                + `${coder.indentString()}\tbe.var["${widget.name}_x"] = x\n`
                + `${coder.indentString()}\tbe.var["${widget.name}_y"] = y\n`
                + inner + '\n'
                + `${coder.indentString()}})\n`
        }
    }
}
